import { BaseService } from '@/base/base.service'
import { Injectable } from '@nestjs/common'
import { HouseRes, RentModel } from '@prisma/client'
import { HouseResDto } from './dto/house-res.dto'
import { PrismaBaseService } from '@/prisma-base/prisma-base.service'
import { RedisService } from '@/redis/redis.service'
import { ConfigService } from '@nestjs/config'

@Injectable()
export class HouseResService extends BaseService<HouseRes, HouseResDto> {
  constructor(
    private readonly prismaBase: PrismaBaseService,
    private readonly redisService: RedisService,
    private readonly config: ConfigService,
  ) {
    super('HouseRes')
  }

  async addHouseRes(data: HouseResDto) {
    const res = await this.prismaBase.houseRes.create({
      data: {
        ...data,
        house_rent: +data.house_rent,
      },
    })
    let loc = res.house_position.split(',')
    let longitude = parseFloat(loc[0])
    let latitude = parseFloat(loc[1])
    try {
      await this.redisService.addGeo(`${res.id}&${res.house_plot}`, [longitude, latitude])
    } catch (e) {
      throw new Error('添加房源位置失败')
    }
    return res.id
  }

  async getHouseResFilter(
    page: number,
    house_peace: string,
    house_use: string,
    min_rent: string,
    max_rent: string,
    house_type: string,
  ) {
    const row = this.config.get('PAGE_ROW')
    let where = {}
    if (min_rent === '' && max_rent === '') {
      where = {
        house_peace: {
          contains: house_peace,
        },
        house_use: {
          contains: house_use,
        },
        house_type: {
          startsWith: house_type,
        },
        house_status: true,
      }
    } else {
      where = {
        house_peace: {
          contains: house_peace,
        },
        house_use: {
          contains: house_use,
        },
        house_type: {
          startsWith: house_type,
        },
        house_rent: {
          gte: +min_rent,
          lte: +max_rent,
        },
        house_status: true,
      }
    }
    const dataList = await this.prismaBase.houseRes.findMany({
      where,
      include: {
        HouseMedia: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
      skip: (+page - 1) * row,
      take: +row,
    })
    const total = await this.prismaBase.houseRes.count({
      where,
    })

    return {
      currentPage: +page,
      pageRow: +row,
      total,
      totalPage: Math.ceil(total / +row),
      data: dataList,
    }
  }

  async searchHouseResByName(page: number, house_plot: string) {
    const row = this.config.get('PAGE_ROW')
    const dataList = await this.prismaBase.houseRes.findMany({
      where: {
        house_plot: {
          contains: house_plot,
        },
        house_status: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
      include: {
        HouseMedia: true,
      },
      skip: (+page - 1) * row,
      take: +row,
    })
    const total = await this.prismaBase.houseRes.count({
      where: {
        house_plot: {
          contains: house_plot,
        },
        house_status: true,
      },
    })
    return {
      currentPage: +page,
      pageRow: +row,
      total,
      totalPage: Math.ceil(total / +row),
      data: dataList,
    }
  }

  async getHouseResDetail(id: string) {
    return await this.prismaBase.houseRes.findUnique({
      where: {
        id,
      },
      include: {
        HouseMedia: {
          select: {
            id: true,
            media_url: true,
            media_type: true,
            houseResId: true,
            createdAt: true,
            isPoster: true,
          },
        },
      },
    })
  }

  async changeResStatus(id: string, house_status: boolean) {
    await this.prismaBase.houseRes.update({
      where: {
        id,
      },
      data: {
        house_status: !house_status,
      },
    })
    return '修改成功'
  }

  async getHouseResMode(page: number, house_mode: RentModel) {
    const row = this.config.get('PAGE_ROW')
    const dataList = await this.prismaBase.houseRes.findMany({
      where: {
        house_mode,
        house_status: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
      include: {
        HouseMedia: {
          select: {
            id: true,
            media_url: true,
            media_type: true,
            houseResId: true,
            createdAt: true,
            isPoster: true,
          },
        },
      },
      skip: (+page - 1) * row,
      take: +row,
    })
    const total = await this.prismaBase.houseRes.count({
      where: {
        house_mode,
        house_status: true,
      },
    })
    return {
      currentPage: +page,
      pageRow: +row,
      total,
      totalPage: Math.ceil(total / +row),
      data: dataList,
    }
  }

  async delHouseRes(id: string, house_plot: string) {
    await this.prismaBase.houseRes.delete({
      where: {
        id,
      },
    })
    try {
      await this.redisService.removeGeo(`${id}&${house_plot}`)
    } catch (e) {
      throw new Error('删除位置失败')
    }
    return '删除成功'
  }

  async editHouseRes(id: string, data: HouseResDto) {
    const oldRes = await this.prismaBase.houseRes.findUnique({
      where: { id },
    })
    const newRes = await this.prismaBase.houseRes.update({
      where: { id },
      data,
    })
    let loc = newRes.house_position.split(',')
    let longitude = parseFloat(loc[0])
    let latitude = parseFloat(loc[1])
    try {
      await this.redisService.removeGeo(`${oldRes.id}&${oldRes.house_plot}`)
      await this.redisService.addGeo(`${newRes.id}&${newRes.house_plot}`, [longitude, latitude])
    } catch (e) {
      throw new Error('修改位置失败')
    }
    return '修改成功'
  }

  async getHouseAdmin(page: number, landload_id: string) {
    const row = this.config.get('PAGE_ROW')
    const dataList = await this.prismaBase.houseRes.findMany({
      where: {
        landload_id,
      },
      include: {
        HouseMedia: true,
      },
      skip: (+page - 1) * row,
      take: +row,
    })
    const total = await this.prismaBase.houseRes.count({
      where: {
        landload_id,
      },
    })
    return {
      currentPage: +page,
      pageRow: +row,
      total,
      totalPage: Math.ceil(total / +row),
      data: dataList,
    }
  }
}
